package test.study.java.jol.samples;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.vm.VM;

import java.io.PrintWriter;

@Slf4j
public class JOLSample_20_Allocation {

    /*
     * The example of allocation addresses.
     *
     * This example shows the addresses of newly allocated objects
     * grow linearly in HotSpot. This is because the allocation in
     * parallel collectors is linear. We can also see it rewinds back
     * to the same offsets -- that's the start of some GC generation.
     *
     * For Parallel-like GCs, while GC adjusts for the allocation rate.
     * For G1-like GCs, the allocation address changes by region size,
     * as collector switches to another region for allocation.
     *
     * Run with test with smaller heap (about 1 GB) for best results.
     */

    public static void main(String[] args) {
        log.info(VM.current().details());

        PrintWriter pw = new PrintWriter(System.out, true);

        long last = VM.current().addressOf(new Object());
        for (int l = 0; l < 1000 * 1000 * 1000; l++) {
            long current = VM.current().addressOf(new Object());

            long distance = Math.abs(current - last);
            if (distance > 4096) {
                pw.printf("Jumping from %x to %x (distance = %d bytes, %dK, %dM)%n",
                        last,
                        current,
                        distance,
                        distance / 1024,
                        distance / 1024 / 1024);
            }

            last = current;
        }

        pw.close();
    }
}
